//
//  Netmanager.m
//  Net2
//
//  Created by student on 16/3/29.
//  Copyright © 2016年 NIIT. All rights reserved.
//

#import "Netmanager.h"
#import <TBXML.h>

//单例


@implementation Netmanager

SingletonM(Netmanager)

+ (BOOL)loginWithName:(NSString *)userName
         WithPassword:(NSString *)password
{
    NSString *str = @"http://localhost:8080/MJServer/login";
    NSString *param = [NSString stringWithFormat:@"username=%@&pwd=%@&type=XML",userName,password];
    NSURL *url = [NSURL URLWithString:str];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    request.HTTPMethod = @"POST";
    
    request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *error;
    
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
    
    TBXML *xml = [[TBXML alloc] initWithXMLData:data error:nil];
    //得到根节点
    TBXMLElement *root = xml.rootXMLElement;
    //节点的名称
    NSString *elementName = [TBXML elementName:root];
//    //节点里的内容
//    NSString *info = [TBXML textForElement:root];
    
    if ([elementName isEqualToString:@"error"]) {
        return NO;
    }
    else{
    return YES;
    }
}


+(NSArray *)requestMovieList{
    NSString *urlStr = @"http://localhost:8080/MJServer/video?method=get&type=JSON";
    
    NSURL *url = [NSURL URLWithString:urlStr];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSArray *arr = [NSArray array];
    
    NSError *error;
    
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
    
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
    
    arr = dict[@"videos"];
    return arr;
}

+(void)loginWithUserName:(NSString *)username
            WithPassword:(NSString *)password
        WithSuccessBlock:(void(^)())successBlock
         WithFailedBlock:(void(^)(NSError *))failBlock{
    NSString *param = [NSString stringWithFormat:@"username=%@&pwd=%@&type=XML",username,password];
    [self requestInfoWithURLStr:param
               WithSuccessBlock:^(NSData *data) {
                   successBlock();
               }
                WithFailedBlock:^(NSError *error) {
                    failBlock(error);
                }];
}

+ (void) requestInfoWithURLStr:(NSString *)urlStr
              WithSuccessBlock:(void(^)(NSData *))successBlock
               WithFailedBlock:(void(^)(NSError *))failedBlock{
    NSString *str = @"http://localhost:8080/MJServer/login";
    NSString *param = urlStr;
    NSURL *url = [NSURL URLWithString:str];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    request.HTTPMethod = @"POST";
    
    request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];
    
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    
    TBXML *xml = [[TBXML alloc] initWithXMLData:data error:nil];
    //得到根节点
    TBXMLElement *root = xml.rootXMLElement;
    //节点的名称
    NSString *elementName = [TBXML elementName:root];
    //节点里的内容
    NSString *info = [TBXML textForElement:root];
    if ([elementName isEqualToString:@"error"]) {
        NSError *error = [NSError errorWithDomain:@"" code:1 userInfo:@{@"error":info}];
        failedBlock(error);
    }
    else{
        successBlock(data);
    }
}



-(void)loginWithUserName:(NSString *)username
            WithPassword:(NSString *)password{
    //URL 网址
    NSString *str = [NSString stringWithFormat:@"http://localhost:8080/MJServer/login?username=%@&pwd=%@&method=get&type=JSON",username,password];
    NSURL *url = [NSURL URLWithString:str];
    NSURLRequest *request = [NSURLRequest requestWithURL:url
                                             cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                         timeoutInterval:10];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
                               
                               if (connectionError == nil) {
                                   NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data
                                                                                        options:NSJSONReadingMutableLeaves
                                                                                          error:nil];
                                   
                                   if (dict[@"error"] == nil) {
                                       [self.delegate loginSuccess];
                                   }
                                   else{
                                       // 定义一个NSError对象
                                       NSError *error = [NSError errorWithDomain:@"com.niit.net2Demo"                           // 域
                                                                            code:1                                    // 错误编号
                                                                        userInfo:@{NSLocalizedDescriptionKey:dict[@"error"]}];  // 错误信息
                                       [self.delegate loninFail:error];
                                   }
                               }
                               else{
                                   [self.delegate loninFail:connectionError];
                               }
                           }];
}

-(void)requestMovieList{
    NSString *urlStr = @"http://localhost:8080/MJServer/video?method=get&type=JSON";
    
    NSURL *url = [NSURL URLWithString:urlStr];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
                                           if (connectionError == nil) {
                                               NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data
                                                                                                    options:NSJSONReadingMutableLeaves
                                                                                                      error:nil];
                                               
                                               if (dict[@"error"] == nil) {
                                                   [self.delegate requestMovieListSuccess:dict[@"videos"]];
                                               }
                                               else{
                                                   // 定义一个NSError对象
                                                   NSError *error = [NSError errorWithDomain:@"com.niit.net2Demo"                           // 域
                                                                                        code:1                                    // 错误编号
                                                                                    userInfo:@{NSLocalizedDescriptionKey:dict[@"error"]}];  // 错误信息
                                                   [self.delegate requestMovieListFail:error];
                                               }
                                           }
                                           else{
                                               [self.delegate loninFail:connectionError];
                                           }

                                       }];

    
}
@end













